package com.group.view;

import com.group.controller.StudentController;
import com.group.model.Student;

import javax.swing.*;
import java.awt.*;
import java.util.Map;

/**
 * @author lenovo
 */
class QueryPanel extends JPanel {
    private JTextField nameField = new JTextField(15);
    private JTextArea resultArea = new JTextArea();
    private JButton queryBtn = new JButton("查询");

    public QueryPanel() {
        setLayout(new BorderLayout());

        // 输入框面板
        JPanel inputPanel = new JPanel();
        inputPanel.add(new JLabel("学生姓名："));
        inputPanel.add(nameField);
        inputPanel.add(queryBtn);

        // 文本区域只读
        resultArea.setEditable(false);

        add(inputPanel, BorderLayout.NORTH);
        add(new JScrollPane(resultArea), BorderLayout.CENTER);

        // 查询事件
        queryBtn.addActionListener(e -> {
            String name = nameField.getText().trim();
            if (name.isEmpty()) {
                resultArea.setText("请输入学生姓名");
                return;
            }

            boolean found = false;
            StringBuilder sb = new StringBuilder();

            for (Student s : StudentController.getAll()) {
                if (s.getName().equals(name)) {  // 精确匹配姓名
                    found = true;
                    sb.append("学号：").append(s.getId()).append("\n");
                    sb.append("姓名：").append(s.getName()).append("\n");
                    sb.append("性别：").append(s.getGender()).append("\n");
                    sb.append("出生日期：").append(s.getBirth()).append("\n");

                    Map<String, Double> scores = s.getScores();
                    sb.append("Math：").append(scores.getOrDefault("Math", 0.0)).append("\n");
                    sb.append("Java：").append(scores.getOrDefault("Java", 0.0)).append("\n");
                    sb.append("PE：").append(scores.getOrDefault("PE", 0.0)).append("\n\n");
                }
            }
            for (Student s : StudentController.getAll()){
                if (s.getName().contains(name)&&!(s.getName().equals(name))) {  // 模糊匹配姓名
                    found = true;
                    sb.append("学号：").append(s.getId()).append("\n");
                    sb.append("姓名：").append(s.getName()).append("\n");
                    sb.append("性别：").append(s.getGender()).append("\n");
                    sb.append("出生日期：").append(s.getBirth()).append("\n");

                    Map<String, Double> scores = s.getScores();
                    sb.append("Math：").append(scores.getOrDefault("Math", 0.0)).append("\n");
                    sb.append("Java：").append(scores.getOrDefault("Java", 0.0)).append("\n");
                    sb.append("PE：").append(scores.getOrDefault("PE", 0.0)).append("\n\n");
                }
            }

            if (!found) {
                resultArea.setText("未找到该学生，请确认姓名输入是否正确。");
            } else {
                resultArea.setText(sb.toString());
            }
        });
    }
}
